<!--
 * @Date: 2024-05-29 11:37:50
 * @LastEditors: 陈俊宇 467724386@qq.com
 * @LastEditTime: 2024-08-14 16:49:08
-->
<template>
    <label class="file-btn-container" for="fileInput">
        <img
            src="@/assets/file.png"
            alt=""
            class="btn"
            :class="{ disabled: disabled }"
            @click="click"
        />
    </label>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { determineFileType } from '@/utils'
import { computed, reactive, inject } from 'vue'

const props = defineProps({
    onChange: {
        type: Function,
        required: true,
    },
})

const iconDisabledData = inject('iconDisabled')

const state = reactive({})

const disabled = computed(() => {
    return iconDisabledData().disabled.value
})

const click = () => {
    if (disabled.value) return

    const input = document.createElement('input')
    input.type = 'file'
    input.style.display = 'none'
    document.body.appendChild(input)
    input.click()
    input.onchange = async (e) => {
        const file = e.target.files[0]
        if (file.size > 50 * 1024 * 1024) {
            ElMessage({
                message: 'The maximum file size is 50MB..',
                type: 'warning',
            })
        } else {
            const fileURL = URL.createObjectURL(file)
            const typeIndex = file.name.lastIndexOf('.')
            const extension = file.name.substring(typeIndex + 1)

            const fileData = {
                loading: true,
                name: file.name.substring(0, typeIndex),
                size: file.size,
                type: file.type,
                extension: file.name.substring(typeIndex + 1),
                localUrl: fileURL,
                url: fileURL,
                progress: 0,
                id: '',
            }

            if (determineFileType(extension) === 'image') {
                await getImageWh(file)
                    .then(({ width, height }) => {
                        // 这里可以做进一步的处理，比如更新Vue组件的状态
                        fileData.width = width
                        fileData.height = height
                    })
                    .catch((error) => {
                        console.error('Error loading Image:', error)
                    })
            }

            if (determineFileType(extension) === 'video') {
                await getVideoWh(file)
                    .then(({ width, height, duration }) => {
                        fileData.width = width
                        fileData.height = height
                        fileData.duration = duration
                        // 进一步处理，如更新Vue组件状态
                    })
                    .catch((error) => {
                        console.error('Error loading video:', error)
                    })
            }

            const blobFile = await fetch(fileURL).then((res) => res.blob())

            fileData.blob = blobFile

            props.onChange(fileData)
        }
    }
}

const getImageWh = (file) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = (e) => {
            const img = new Image()
            img.onload = () => {
                const width = img.naturalWidth
                const height = img.naturalHeight
                resolve({ width, height }) // 解析Promise并返回宽度和高度
            }
            img.onerror = reject // 如果图片加载失败，拒绝Promise
            img.src = e.target.result
        }
        reader.readAsDataURL(file)
    })
}
const getVideoWh = (file) => {
    return new Promise((resolve, reject) => {
        const video = document.createElement('video')
        video.preload = 'metadata' // 预加载元数据
        video.onloadedmetadata = () => {
            const width = video.videoWidth
            const height = video.videoHeight
            const duration = video.duration
            resolve({ width, height, duration }) // 解析Promise并返回宽度、高度和时长
        }
        video.onerror = reject // 如果加载失败，拒绝Promise
        video.src = URL.createObjectURL(file) // 使用createObjectURL创建一个指向文件的URL
    })
}
</script>

<style lang="scss" scoped>
.file-btn-container {
    width: 23px;
    height: 20px;
    margin-left: 12px;
    display: flex;
    justify-content: center;
    align-content: center;
    .btn {
        width: 23px;
        height: 20px;
        cursor: pointer;
    }
    .disabled {
        opacity: 0.6;
        cursor: not-allowed;
    }
}
</style>
